<template>
  <div class="login-container">
    <van-nav-bar title="登录" left-arrow @click-left="$router.go(-1)" />
    <van-form ref="form" @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        type="number"
        name="mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        placeholder="请输入手机号"
        maxlength="11"
        :rules="rules.mobile"
      />
      <van-field
        v-model="user.code"
        type="number"
        maxlength="6"
        name="code"
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        placeholder="请输入验证码"
        :rules="rules.code"
      >
        <template #button>
          <van-button
            v-if="countDownShow"
            native-type="button"
            size="small"
            type="primary"
          >
            <van-count-down :time="3000" format="ss 秒" @change="change" />
          </van-button>
          <van-button
            v-else
            native-type="button"
            size="small"
            type="primary"
            @click="sendSms"
            >发送验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button block type="info" native-type="submit">登录</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
/**
 * 登录功能思路：
 * 1. 先绘制页面
 * 2. 调用登录接口，获取token，保证正向流程能通
 * 3. 细节优化：表单校验等
 */
import { loginApi, smsApi } from '@/api/Login'
export default {
  data() {
    return {
      countDownShow: false, // 控制倒计时按钮的显示
      // 用户输入的数据
      user: {
        mobile: '',
        code: ''
      },
      // 表单校验规则
      rules: {
        mobile: [
          { required: true, message: '请填写用户名' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号不正确' }
        ],
        code: [
          { required: true, message: '请填写密码' },
          { pattern: /^\d{6}$/, message: '验证码错误' }
        ]
      }
    }
  },
  methods: {
    // 发送验证码
    async sendSms() {
      // 发送之前手动校验一下手机号是否合法
      await this.$refs.form.validate('mobile')
      this.countDownShow = true
      try {
        await smsApi(this.user.mobile)
        this.$toast.success('验证码已发送')
      } catch (error) {
        // 捕获一下发送验证码失败的情况，抛出错误提示
        const { status, data } = error.response
        if (status === 429) {
          this.$toast.fail(data.message)
        } else {
          this.$toast.fail('发送失败，请稍后再试')
        }
      }
    },
    // 监听倒计时时间变化
    change(time) {
      if (time.seconds === 0) this.countDownShow = false
    },
    // 表单提交，登录操作
    async onSubmit() {
      // duration: 展示时长(ms)，值为 0 时，toast 不会消失;默认2000ms
      this.$toast.loading({
        message: '登录中...',
        duration: 0,
        forbidClick: true
      })
      try {
        const res = await loginApi(this.user)
        this.$store.commit('setUserToken', res.data.data)
        this.$toast.success('登录成功')
        this.$router.back()
      } catch (error) {
        const { status, data } = error.response
        if (status === 400) {
          this.$toast.fail(data.message)
        } else {
          this.$toast.fail('登录失败，请稍后再试')
        }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.login-container {
  .van-nav-bar {
    background-color: #3296fa;
    /deep/.van-icon {
      color: #fff;
    }
  }
  :deep(.van-nav-bar__title) {
    color: #fff;
  }
  .van-count-down {
    color: #fff;
  }
}
</style>